<template>
    <el-dialog
      :title="title"
      :visible.sync="openDlg"
      width="40%"
      append-to-body
      destroy-on-close
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-row>
          <el-col v-if="scholarshipTypeArr.some((item) => { return item.code == allocationType})" :span="24">
            <div class="residue">
              <div class="residue-item">
                本科剩余名额：{{allot.remainPersonNum + rowData.personNumber}}人
              </div>
              <div class="residue-item">
                专科剩余名额：{{allot.remainPersonNum2 + rowData.personNumber2}}人
              </div>
            </div>
          </el-col>
          <el-col v-if="allocationType == 'subsidy'" :span="24">
            <div class="residue">
              <div class="residue-item" v-for="item in subsidyType" :key="item.typeId">
                {{item.diffName}}剩余名额：{{allot['diffName'+item.typeId+'sy']}}人
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="当前分配">
              {{form.collegeName}}
              <template v-if="allocationType == 'subsidyteacher'">
                <div>
                  可分配金额/元：{{ypfMoney}}
                </div>
                <div>
                  分配金额/元：{{allotmenAmount}}
                </div>
              </template>
            </el-form-item>
          </el-col>
          <template v-if="scholarshipTypeArr.some((item) => { return item.code == allocationType})">
            <el-col :span="24">
              <el-form-item label="本科名额" prop="personNumber">
                <el-input-number style="width:100%" v-model.number="form.personNumber" :step="1" :min="0" step-strictly controls-position="right" placeholder="请输入国家奖学金名额" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="专科名额"  prop="personNumber2">
                  <el-input-number style="width:100%" v-model.number="form.personNumber2" :step="1" :min="0" step-strictly controls-position="right" placeholder="请输入国家励志奖学金名额" />
              </el-form-item>
            </el-col>
          </template>
          <template v-if="allocationType == 'subsidy' || allocationType == 'subsidyteacher'">
            <el-col :span="24" v-for="item in subsidyTYpes" :key="item.diffId">
              <el-form-item :label="`${item.diffName}（${item.diffMoney}元/人）`">
                <el-row>
                  <el-col :span="12">
                   本科： <el-input-number style="width:100%" v-model.number="item.personNum" :step="1" :min="0" step-strictly controls-position="right" />
                  </el-col>
                  <el-col :span="12">
                  专科：<el-input-number style="width:100%" v-model.number="item.personNum2" :step="1" :min="0" step-strictly controls-position="right" />
                  </el-col>
                </el-row>
                
              </el-form-item>
            </el-col>
          </template>

          <template v-if="allocationType == 'schoolScholarship'">
            <el-col :span="24" v-for="item in schoolScholarshipType" :key="item.id">
              <el-form-item :label="item.typeName">
                <el-row>
                  <el-col :span="12">
                   本科： <el-input-number style="width:100%" v-model.number="item.personNum" :step="1" :min="0" step-strictly controls-position="right" />
                  </el-col>
                  <el-col :span="12">
                  专科：<el-input-number style="width:100%" v-model.number="item.personNum2" :step="1" :min="0" step-strictly controls-position="right" />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </template>
          
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openDlg = false">取 消</el-button>
      </div>
    </el-dialog>
</template>

<script>

import { 
  editScholarshipAllocation,
  collageAllocationed,
  editCollageAllocationed,
  editSchoolScholarshipAllocation
} from "@/api/poorStudent-scholarship/allocation.js";

import {
  scholarshipTypeArr
} from "@/views/poorStudent-scholarship/dict.js"
export default {
    name:"allocationEdit",
    props:{
      subsidyType:{
        type:Array,
        default: []
      },
      yearStr:{
          type: String,
          default: ''
      }
    },
    data () {
        return {
            title: '分配',
            openDlg: false,
            // 表单参数
            form: {
              personNum: null,
              personNum2: null
            },
            rowData:{},
            // 表单校验
            rules: {
              personNum: [
                { required: true, message: '请输入本科名额', trigger: 'blur' }
              ],
              personNum2: [
                { required: true, message: '请输入专科名额', trigger: 'blur' }
              ],
              personNumber: [
                { required: true, message: '请输入本科名额', trigger: 'blur' }
              ],
              personNumber2: [
                { required: true, message: '请输入专科名额', trigger: 'blur' }
              ],
            },
            allocationType: "",
            rowData: {},
            allot: {},
            subsidyTYpes:[],
            ypfMoney: [],
            schoolScholarshipType:[],
            scholarshipTypeArr
        }
    },
    computed: {
      allotmenAmount () {
        return this.subsidyTYpes.reduce((_num, item) => {
          if(item.diffMoney && item.personNum) {
            _num += item.diffMoney * item.personNum
          }
          if(item.diffMoney && item.personNum2) {
            _num += item.diffMoney * item.personNum2
          }
          return _num
        }, 0)
      }
    },
    methods:{
        open (rowData, type, allot) {
            console.log(rowData, type, allot)
            this.rowData = {...rowData} 
            this.form = {...rowData}
            this.allocationType = type
            this.allot = allot
            this.openDlg = true
            if (this.allocationType == 'subsidy' || this.allocationType == 'subsidyteacher') {
              this.getCollageAllocationed()
            }
            if (this.allocationType == 'schoolScholarship') {
              this.form.collegeName = rowData.collageName
              this.schoolScholarshipType = rowData.scholarshipTypeList
            }
        },
        getCollageAllocationed () {
          collageAllocationed({
            yearStr: this.yearStr,
            collageId: this.form.collegeId
          }).then((res) => {
            this.subsidyTYpes = res
            this.ypfMoney = res.reduce((_num, item) => {
              if(item.diffMoney && item.personNum) {
                _num += item.diffMoney * item.personNum
              }
              if(item.diffMoney && item.personNum2) {
                _num += item.diffMoney * item.personNum2
              }
              return _num
            }, 0)
          })
        },
        submitForm () {
          this.$refs["form"].validate((valid) => {
            if (valid) {
              if (this.allocationType == 'schoolScholarship') {
                editSchoolScholarshipAllocation({
                  yearStr: this.yearStr,
                  collageId: this.form.collageId,
                  collageName: this.form.collageName,
                  scholarshipTypeList: this.schoolScholarshipType.map((item)=>{
                    return {
                      id: item.id,
                      personNum: item.personNum,
                      personNum2: item.personNum2,
                      personNum3: item.personNum3,
                      typeId: item.typeId
                    }
                  })
                }).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.openDlg = false;
                  this.$emit("onSearch")
                });
              } else if (scholarshipTypeArr.some((item) => { return item.code == this.allocationType })) {
                if (this.form.personNumber > this.allot.remainPersonNum + this.rowData.personNumber) {
                  this.$modal.msgWarning("本科分配名额不能大于剩余名额！");
                  return
                }
                if (this.form.personNumber2 > this.allot.remainPersonNum2 + this.rowData.personNumber2) {
                  this.$modal.msgWarning("专科分配名额不能大于剩余名额！");
                  return
                }
                editScholarshipAllocation(this.yearStr,this.form).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.openDlg = false;
                  this.$emit("onSearch")
                });
              } else {
                for (const index in this.subsidyTYpes) {
                  if (this.subsidyTYpes[index].personNum === undefined || this.subsidyTYpes[index].personNum  === "" || this.subsidyTYpes[index].personNum === null) {
                    this.$modal.msgError("请输入"+ this.subsidyTYpes[index].diffName +"名额（本科）");
                    return
                  }
                  if (this.subsidyTYpes[index].personNum2 === undefined || this.subsidyTYpes[index].personNum2  === "" || this.subsidyTYpes[index].personNum2 === null) {
                    this.$modal.msgError("请输入"+ this.subsidyTYpes[index].diffName +"名额（专科）");
                    return
                  }
                }
                if (this.allocationType == 'subsidyteacher' && this.allotmenAmount !== this.ypfMoney) {
                  this.$modal.msgError("分配金额不能大于或小于可分配金额");
                  return
                }
                editCollageAllocationed({
                  yearStr: this.yearStr,
                  collegeId: this.form.collegeId,
                  collegeName: this.form.collegeName,
                  collegePlanId: this.form.id,
                  diffCollPlanTypeReqList: this.subsidyTYpes.map((item)=>{
                    return {
                      diffTypeName: item.diffName,
                      personNum: item.personNum,
                      personNum2: item.personNum2,
                    }
                  })
                }).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.openDlg = false;
                  this.$emit("onSearch")
                });
              }
            }
          });
        },
    }

}
</script>

<style lang="scss" scoped>
  .residue{
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    &-item + &-item{
      margin-left: 10px;
    }
  }
</style>